'use strict';

const path = require('path');
const gulp = require('gulp');
const less = require('gulp-less');
//const sass = require('gulp-sass');
const gutil = require('gulp-util');
const uglify = require('gulp-uglify');
const clean = require('gulp-clean');
const plumber = require('gulp-plumber');
const gulpsync = require('gulp-sync')(gulp);
const ngAnnotate = require('gulp-ng-annotate');
const sourcemaps = require('gulp-sourcemaps');
const buffer = require('vinyl-buffer');
const watchify = require('watchify');
const source = require('vinyl-source-stream');
const browserify = require('browserify');
const browserSync = require('browser-sync').create();
const ngHtml2Js = require('browserify-ng-html2js');
const reload = browserSync.reload;


const buildjs = path.resolve(__dirname,'build/scripts');
const buildStyles = path.resolve(__dirname,'build/styles');

//应用模块入口
const app = path.resolve(__dirname,'src/config/app.js');

//应用组件模块入口
const components = path.resolve(__dirname,'src/config/app.js');

const browser = watchify(browserify(getOptions(app)));

//应用模块JS热部署
gulp.task('app:modules:watch', appModulesWatch);
browser.on('update', appModulesWatch);
browser.on('log', gutil.log);

function appModulesWatch() {
  return browser.bundle()
    .on('error', gutil.log.bind(gutil, 'browserify Error ......'))
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(ngAnnotate())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write("./"))
    .pipe(gulp.dest(buildjs))
    .pipe(reload({
        stream: true
    }));
}

//应用模块 for build
gulp.task('app:modules', ()=> {
    browserify({
        entries: [
            app
        ]
    })
    .bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(ngAnnotate())
    .pipe(uglify({ mangle: false }))
    .pipe(gulp.dest(buildjs));
});


//引入的第三方框架 js
gulp.task('app:vendor', ()=> {
    browserify({
        entries: [
            path.resolve(__dirname,'src/config/vendor.js')
        ]
    })
    .bundle()
    .pipe(source('vendor.min.js'))
    .pipe(buffer())
    .pipe(uglify({ mangle: false }))
    .pipe(gulp.dest(buildjs));
});


//页面模板打包 for watch
gulp.task('app:modules:templates', ()=> {
    browserify({
        entries: [
            path.resolve(__dirname,'src/config/templates.js')
        ]
    })
    .transform(ngHtml2Js({
        module: 'baocloud.templates',
        baseDir: 'src/modules/'
    })).bundle()
    .pipe(source('templates.js'))
    .pipe(buffer())
    .pipe(uglify({ mangle: false }))
    .pipe(gulp.dest(buildjs))
    .pipe(reload({
        stream: true
    }));
});

//组件模板打包  for watch
gulp.task('app:components:templates', ()=> {
    browserify({
        entries: [
            path.resolve(__dirname,'src/components/templates.js')
        ]
    })
    .transform(ngHtml2Js({
        module: 'baocloud.components.templates',
        baseDir: 'src/components/'
    })).bundle()
    .pipe(source('components.tpls.js'))
    .pipe(buffer())
    .pipe(uglify({ mangle: false }))
    .pipe(gulp.dest(buildjs))
    .pipe(reload({
        stream: true
    }));
});

// gulp.task('sass', ()=> {
//     return gulp.src(path.resolve(__dirname,'src/themes/sass/**/*.scss'))
//         .pipe(sass.sync().on('error', sass.logError))
//         .pipe(gulp.dest(buildStyles))
//         .pipe(reload({
//             stream: true
//         }));
// });

gulp.task('less', ()=> {
    return gulp.src([
            path.resolve(__dirname,'src/themes/app.less'),
            path.resolve(__dirname,'src/themes/bootstrap.less')
        ])
        .pipe(plumber()) //错误处理 {errorHandler: gutil.beep()}
        .pipe(less({
            paths: [ path.join(__dirname,'node_modules/bootstrap/less') ]
        }))
        .pipe(gulp.dest(buildStyles))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('font', ()=> gulp.src([
                            path.resolve(__dirname,'src/assets/fonts/*.@(eot|woff|ttf|svg)'),
                            path.resolve(__dirname,'node_modules/font-awesome/fonts/*.@(eot|woff|ttf|svg|otf|woff2)')
                        ])
                        .pipe(gulp.dest(path.resolve(__dirname,'build/fonts')))
);

gulp.task('image', ()=> gulp.src(path.resolve(__dirname,'src/assets/images/**/*.*'))
                            .pipe(gulp.dest(path.resolve(__dirname,'build/images')))
);

gulp.task('index', ()=> gulp.src(path.resolve(__dirname,'src/index.html'))
                            .pipe(gulp.dest(path.resolve(__dirname,'build')))
);

gulp.task('copy',['font','image','index']);

gulp.task('server', ['app:modules:watch', 'app:components:templates', 'app:modules:templates', 'app:vendor', 'less', 'copy'], ()=> {
    browserSync.init({
        server: {
            baseDir: ['src','build'],
            index: "index.html"
        }
        // open: "local",
        // browser: 'google chrome'
    });

    gulp.watch(path.resolve(__dirname,'src/modules/**/*.html'), ['app:modules:templates']);
    gulp.watch(path.resolve(__dirname,'src/components/**/*.html'), ['app:components:templates']);
    gulp.watch(path.resolve(__dirname,'src/**/*.less'), ['less']);
    //gulp.watch(path.resolve(__dirname,'src/themes/less/**/*.less'), ['less']);
    //gulp.watch(path.resolve(__dirname,'src/themes/sass/**/*.sass'), ['sass']);
    gulp.watch([
        path.resolve(__dirname,'src/views/**/*.html'),
        path.resolve(__dirname,'src/*.html')
    ]).on('change', reload);
});

gulp.task('clean', ()=> {
    return gulp.src('./build', {read: false})
        .pipe(clean());
});

gulp.task('build', gulpsync.sync(['clean', 'app:modules', 'app:components:templates', 'app:modules:templates', 'app:vendor', 'less', 'copy']));

gulp.task('default', ['server'], ()=> {
    gutil.log('预编译结束......');
});


function getOptions(filePath){
    return {
        entries: [
            filePath
        ],
        debug: true,
        cache: {},
        packageCache: {}
        //plugin: [watchify]
    }
}